﻿using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections;
using System.Configuration;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Jungle.Code.Core;
using Jungle.Code.DAL;
using System.Collections.Generic;
using Jungle.Code.Utils;
using Jungle.Code.BLL;

using Jungle.Prodamo.AdvertManager;
using Jungle.Prodamo.MostNeedFunctions;
using Jungle.Prodamo.Core;
using Jungle.Prodamo.PaySystem;

    public partial class FileObmen : BaseUserModule
	{
        private int userId;

        SessionKeeper thisSession = new SessionKeeper();

        protected override void OnInit(EventArgs e)
        {
            thisSession.SessionId = Session.SessionID.ToString();
            thisSession.GetData();

            if (thisSession.UserId != -1)
            {
                tr_Email.Visible = false;
                tr_FastKey.Visible = false;
                tr_Password.Visible = false;
            }

            btn1.PostBackUrl = Request.RawUrl;            
            base.OnInit(e);
        }
        protected override void Render(HtmlTextWriter writer)
        {
            if (thisSession.UserId != -1)
            {
                if (Request["cmd"] != null)
                {
                    switch (Request["cmd"])
                    { 
                        case "myfiles":
                            GetMyFilesContent(writer);
                            break;
                        case "newfile":
                            {
                                form_newfile.Visible = true;
                                break;
                            }
                        case "freshfile":
                            GetFreshFilesContent(writer);
                            break;
                    }
                }
                else
                    writer.Write("Добро пожаловать на наш файлобменник");
            }

            base.Render(writer);
        }

        protected void btn1_Click(object sender, EventArgs e)
        {
            ccJoin.ValidateCaptcha(tb_Cap.Text);
            if (thisSession.UserId != -1)
            {
                AddFile();
            }
            else
            {
                if (tb_FastKey.Text.Trim().Length == 6)
                {
                    FastEnter();
                }
                else
                {
                    UserManager um = new UserManager();
                    um.NickName = tb_Email.Text;
                    um.Password = Functions.getMd5Hash(tb_Password.Text.Trim());

                    if (um.Login())
                    {
                        thisSession.SessionId = Session.SessionID.ToString();
                        thisSession.UserId = um.UserId;
                        thisSession.UserLogin = um.NickName;
                        thisSession.AdminLogin = "none";

                        thisSession.Create();

                        AddFile();
                    }
                    else
                    {
                        if (!um.CheckNickName())
                        {
                            ValidBlock.InnerHtml = "Пользователь с таким Email уже зарегистрирован. Если это вы, то вы просто ввели неверный пароль.";
                        }
                        else
                        {
                            FastRegister();
                            if (um.Login())
                            {
                                thisSession.SessionId = Session.SessionID.ToString();
                                thisSession.UserId = um.UserId;
                                thisSession.UserLogin = um.NickName;
                                thisSession.AdminLogin = "none";

                                thisSession.Create();

                                AddFile();
                            }
                        }
                    }
                }
            }
        }
        protected void AddFile()
        { 
            if (fu1.HasFile && ccJoin.UserValidated)
            {
                fu1.PostedFile.SaveAs(Server.MapPath("UpFiles/" + fu1.FileName));

                UploadFiles up = new UploadFiles();
                up.Title = tb_Title.Text;
                up.UserId = thisSession.UserId;
                up.FileLink = UrlHelper.GetSiteUrl() + "/UpFiles/" + fu1.FileName;
                up.Enabled = chb_Enabled.Checked;
                
                up.Add();

                Response.Redirect(UrlHelper.GetSiteUrl() + "/ru/my_files.aspx?cmd=myfiles");
            }
            else
            {
                ValidBlock.InnerHtml = "Вы неверно ввели код проверки, либо не выбрали файл";
            }
        }
        protected HtmlTextWriter GetMyFilesContent(HtmlTextWriter writer)
        {
            UploadFiles fu = new UploadFiles();
            fu.UserId = thisSession.UserId;
            fu.GetByUser();
            writer.AddAttribute(HtmlTextWriterAttribute.Width, "100%");
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "advm_table");
            writer.RenderBeginTag(HtmlTextWriterTag.Table);
            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "advm_td");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("<strong>ID фала</strong>");
            writer.RenderEndTag();
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "advm_td");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("<strong>Заголовок</strong>");
            writer.RenderEndTag();
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "advm_td");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("<strong>Ссылка</strong>");
            writer.RenderEndTag();
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "advm_td");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("<strong>Статус</strong>");
            writer.RenderEndTag();
            writer.RenderEndTag();

            bool c = true;
            foreach (UploadFiles ff in fu.FileList)
            {
                if (!c)
                {
                    writer.AddAttribute("style", "background-color: #F1F1F1;");
                    c = true;
                }
                else c = false;
                writer.RenderBeginTag(HtmlTextWriterTag.Tr);
                writer.RenderBeginTag(HtmlTextWriterTag.Td);
                writer.Write(ff.FileId.ToString());
                writer.RenderEndTag();
                writer.RenderBeginTag(HtmlTextWriterTag.Td);
                writer.Write(ff.Title);
                writer.RenderEndTag();
                writer.RenderBeginTag(HtmlTextWriterTag.Td);
                    writer.AddAttribute(HtmlTextWriterAttribute.Href, ff.FileLink);
                    writer.RenderBeginTag(HtmlTextWriterTag.A);
                    writer.Write(ff.FileLink);
                    writer.RenderEndTag();
                writer.RenderEndTag();
                writer.RenderBeginTag(HtmlTextWriterTag.Td);
                if (ff.Enabled) writer.Write("Доступен");
                else
                    writer.Write("Заблокирован");
                writer.RenderEndTag();
                writer.RenderEndTag();                
            }

            writer.RenderEndTag();

            return writer;
        }
        protected HtmlTextWriter GetFreshFilesContent(HtmlTextWriter writer)
        {
            UploadFiles fu = new UploadFiles();
            fu.GetAll();

            writer.Write("<strong>Свежие файлы</strong>");
            writer.AddAttribute(HtmlTextWriterAttribute.Width, "100%");
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "advm_table");
            writer.RenderBeginTag(HtmlTextWriterTag.Table);
            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("<strong>ID фала</strong>");
            writer.RenderEndTag();
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("<strong>Заголовок</strong>");
            writer.RenderEndTag();
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("<strong>Ссылка</strong>");
            writer.RenderEndTag();
            writer.RenderEndTag();

            foreach (UploadFiles ff in fu.FileList)
            {
                if (ff.Enabled)
                {
                    writer.RenderBeginTag(HtmlTextWriterTag.Tr);
                    writer.RenderBeginTag(HtmlTextWriterTag.Td);
                    writer.Write(ff.FileId.ToString());
                    writer.RenderEndTag();
                    writer.RenderBeginTag(HtmlTextWriterTag.Td);
                    writer.Write(ff.Title);
                    writer.RenderEndTag();
                    writer.RenderBeginTag(HtmlTextWriterTag.Td);
                    writer.AddAttribute(HtmlTextWriterAttribute.Href, UrlHelper.GetSiteUrl() + ff.FileLink);
                    writer.RenderBeginTag(HtmlTextWriterTag.A);
                    writer.Write(UrlHelper.GetSiteUrl() + ff.FileLink);
                    writer.RenderEndTag();
                    writer.RenderEndTag();
                    writer.RenderBeginTag(HtmlTextWriterTag.Td);
                    writer.RenderEndTag();
                    writer.RenderEndTag();
                }
            }
            writer.RenderEndTag();

            return writer;
        }


        protected void FastRegister()
        {
            if (tb_Email.Text.IndexOf("@") != -1)
            {
                UserManager um = new UserManager();
                um.NickName = tb_Email.Text.Trim();

                string password = tb_Password.Text.Trim();
                um.Fname = "Безымянный";
                um.Oname = "Безымянный";
                um.Iname = "Безымянный";
                um.Email = um.NickName;
                um.Sex = true;
                um.Organization = um.NickName;
                um.Edrpou = "NONE";
                um.WorkTime = "NONE";
                um.Web = "NONE";
                um.Logo = "~/Images/1px.gif";
                um.Map = "~/Images/1px.gif";
                um.Deliver = "";
                um.Credit = "";
                um.Country = "1";
                um.Zip = "00000";
                um.City = "1";
                um.Address = "нет";
                um.Phone = "";
                um.Faks = "";
                um.BirthDay = DateTime.Now;
                um.Password = Functions.getMd5Hash(password);
                um.UsertType = true;
                um.FastKey = GetRandom("");
                um.Add();

                Account acc = new Account();
                acc.CreateAccount(um.UserId);

                string body = "Вы были зарегистрированы на prodamo.com. Данные для доступа: Email:" + um.NickName + ". Password: " + password + ". Ключ быстрого доступа: " + um.FastKey;
                um.SendEmail(um.Email, "prodamo.com: подтверждение регистрации", body);

            }
            else ValidBlock.InnerHtml = "Вы ввели некорректный Email";
        }
        protected void FastEnter()
        {
            UserManager um = new UserManager();
            um.FastKey = tb_FastKey.Text;
            um.GetByFastKey();

            if (um.UserId != 0)
            {
                if (um.Login())
                {
                    thisSession.UserId = um.UserId;
                    thisSession.SessionId = Session.SessionID.ToString();
                    thisSession.UserLogin = um.NickName;
                    thisSession.AdminLogin = "none";
                    thisSession.Create();

                    AddFile();
                }
            }
            else
            {
                ValidBlock.InnerHtml = "Вы ввели некорректный код";
            }
        }
        protected string GetRandom(string str)
        {
            string mask = "1234567890qwertyuiopasdfghjklzxcvbnm";
            System.Random rnd = new Random();
            for (int i = 0; i < 6; i++)
            {
                str += mask[rnd.Next(0, 35)];
            }
            return str;
        }

	}
